#!/usr/bin/perl
use strict;
use warnings;

my @output;
my @currentTemp;
my $highTemp;
my $criticalTemp;
my $avgTemp;
my $badTemp = 0;

unless(`which sensors`)
{
	print "lm-sensors not installed\n";
	exit 3; #program is not installed
}

@output = `sensors 2>&1 |grep "Core " | sed 's/°/ /g'`;

if(@output < 1)
{
	print "No CPU sensor found on this device - Suggest removal of this check\n";
	exit 3; #box does not have sensors - thus, status unknown
}
if($output[0] eq 'No sensors found!')
{
	print "Program lm-sensors installed, no sensors found. Run sudo sensors-detect and load the kernel modules\n";
	exit 3; #box (might) have sensors, but it cannot open them for reading
}


#Allow passing arguements to set temperature ranges for specified hosts
$highTemp = $ARGV[0] if exists $ARGV[0];
$criticalTemp = $ARGV[1] if exists $ARGV[1];

foreach my $line (@output)
{
	chomp($line);
	$line =~ s/\s+/ /g;
	my @core = split(/ /, $line);

	#Temperature of cores
	$core[2] = substr $core[2], 1;
	push(@currentTemp, $core[2]);

	#High temp (assume the same for all cores)
	$core[6] = substr $core[6], 1;
	$highTemp = $core[6] if !exists $ARGV[0];

	#Critical temperature (Assume same for all cores)
	$core[10] = substr $core[10], 1;
	$criticalTemp = $core[10] if !exists $ARGV[1];
}

foreach my $core (@currentTemp)
{
    if($core < 10)
    {
        #assume temperature to be wrong and thus hostile to results
        $badTemp++;
    }
    else
    {
	    $avgTemp += $core;
    }
}
$avgTemp = $avgTemp/(@currentTemp - $badTemp);

print "Average temperature: $avgTemp; System 'high' temperature: $highTemp; System 'crit' temperature: $criticalTemp; Spread out over " . (@currentTemp-$badTemp) . " cores\n";

if($avgTemp < $highTemp)
{
	exit 0; #temperature is normal/low
}
elsif($avgTemp >= $highTemp)
{
	if($avgTemp >= $criticalTemp)
	{
		exit 2; #Temperature is in the critical range
	}
	else
	{
		exit 1; #Gettin a lil warm in here isin't it?
	}
}
